import urllib.request
import socket
import urllib.error

import urllib.parse

def baseDemo():

    '''
        对一些属性信息进行打印
    '''
    response = urllib.request.urlopen("https://www.python.org")

    print(response.read().decode('utf-8')) # 输出网页中所有的内容

    print(type(response)) # 输出response 的类型

    print(response.status) # 200：表示请求成功　404：表示网页未找到

    print(response.getheaders()) # 请求头

    print(response.getheader('Server')) # 具体访问　头信息中　Server 元组



def timeoutDemo():

    '''
        time 参数的使用　案例
            网页超时将　返回
    '''
    try:
        response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
    except urllib.error.URLError as e:
        if isinstance(e.reason, socket.timeout):
            print('Time out')


def defineRequestHead_1():
    '''自定义一个请求头　方式一'''
    url = 'http://httpbin.org/post'

    headers = {
        'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
        'Host': 'httpbin.org'
    }

    dict = {
        'name': 'Germey'
    }

    data = bytes( urllib.parse.urlencode(dict), encoding = 'utf8')
    req = urllib.request.Request(url=url, data=data, headers=headers, method='POST')
    response = urllib.request.urlopen(req)
    print(response.read().decode('utf-8'))


def defineRequestHead_2():
    '''自定义一个请求头 方式二'''
    url = 'http://httpbin.org/post'

    # headers = {
    #     'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
    #     'Host': 'httpbin.org'
    # }

    dict = {
        'name': 'Germey'
    }

    data = bytes( urllib.parse.urlencode(dict), encoding = 'utf8')
    req = urllib.request.Request(url=url, data=data, method='POST')

    req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')

    response = urllib.request.urlopen(req)
    print(response.read().decode('utf-8'))


def handleError():
    """
        处理异常错误
    """
    try:
        response = urllib.request.urlopen('http://cuiqingcai.com/index.htm')
    except urllib.error.HTTPError as e:
        print(e.reason,e.code, e.headers, sep='\n')
    except urllib.error.URLError as e:
        print(e.reason)
    else:
        print('Request Successfully.')

handleError()
